/**
 * spark_src
 */
package com.xiongyingqi.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;

/**
 * @author XiongYingqi
 * @version 2013-6-25 下午9:41:57
 */
public class ComparatorHelper<T> {

	/**
	 * 按照日期进行排序 <br>
	 * 2013-6-25 下午9:46:45
	 * 
	 * @param collection
	 *            要排序的集合
	 * @param field
	 *            指定排序的时间字段
	 * @param asc
	 *            是否按正序排序
	 * @return List
	 */
	public List sortByDateTime(Collection<? extends T> collection,
			final Field field, final boolean asc) {
		if (collection == null) {
			return null;
		}
		List list = new ArrayList();
		list.addAll(collection);
		Collections.sort(list, new Comparator<T>() {
			@Override
			public int compare(T o1, T o2) {
				Object object = invokeMethod(o1, field);
				Object object2 = invokeMethod(o2, field);
				if (object == null || object2 == null) {
					return 0;
				}
				int value = 0;
				if (object instanceof Date) {
					Date v1 = (Date) object;
					Date v2 = (Date) object2;

					if (v1.getTime() < v2.getTime()) {
						value = -1;
					} else if (v1.getTime() > v2.getTime()) {
						value = 1;
					}
					if (!asc) {
						value = -value;
					}
				}
				return value;
			}

		});
		return list;
	}

	private Object invokeMethod(Object target, Field filed) {
		Object returnObject = null;
		Class clazz = target.getClass();
		String fieldName = filed.getName();
		String methodName = "get" + fieldName.substring(0, 1).toUpperCase()
				+ fieldName.substring(1);
		try {
			Method method = clazz.getMethod(methodName);
			returnObject = method.invoke(target);
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return returnObject;
	}

}
